package com.fmsz.xmly.fragments.findfgts;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.fmsz.xmly.R;
import com.fmsz.xmly.activitys.broadcast.LocalRadioActivity;
import com.fmsz.xmly.activitys.broadcast.ProvinceListActivity;
import com.fmsz.xmly.adapters.broadcast.ListViewAdapter;
import com.fmsz.xmly.adapters.broadcast.RecycleViewAdapter;
import com.fmsz.xmly.application.MyApplication;
import com.fmsz.xmly.callbacks.MyLocationListener;
import com.fmsz.xmly.callbacks.OnLocationFinishListener;
import com.fmsz.xmly.entitys.broadcast.BroadCastEntity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class FindBroadcastFragment extends Fragment implements Callback<BroadCastEntity>, View.OnClickListener, OnLocationFinishListener {

    private View view;
    private static final String TAG = "FindBroadcastFragment";
    private RecyclerView recycleView;
    private RecycleViewAdapter adapter;
    private ListView lv_top;
    private ListView lv_end;
    private ListViewAdapter top_adapter;
    private ListViewAdapter end_adapter;
    private LinearLayout btn_group;
    private int[] btnIds = new int[]{R.id.local_btn,R.id.country_btn,R.id.province_btn,R.id.internet_btn};

    public LocationClient mLocationClient = null;
    public BDLocationListener myListener ;
    private String provinceName;
    private SharedPreferences preferences;

    public FindBroadcastFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_find__broadcast_, container, false);
            initView(view);
            initData();
            initLocation();
        }
        return view;
    }

    //初始化数据
    private void initData() {
        preferences = getContext().getSharedPreferences("userLocation", Context.MODE_PRIVATE);
        mLocationClient = new LocationClient(getContext());     //声明LocationClient类
        myListener = new MyLocationListener(mLocationClient,this);
        mLocationClient.registerLocationListener( myListener );
        mLocationClient.start();
        MyApplication application = (MyApplication) getActivity().getApplication();
        //加载广播页面数据
        application.getBroadService().getBroadData().enqueue(this);
    }

    //初始化UI
    private void initView(View view) {
        recycleView = ((RecyclerView) view.findViewById(R.id.recycle_find_broad));
        recycleView.setLayoutManager(new GridLayoutManager(getContext(),4));
        adapter = new RecycleViewAdapter(getContext());
        recycleView.setAdapter(adapter);
        lv_top = ((ListView) view.findViewById(R.id.broad_lv_top));
        lv_end = ((ListView) view.findViewById(R.id.broad_lv_end));
        top_adapter = new ListViewAdapter(getContext(),ListViewAdapter.TAG1);
        end_adapter = new ListViewAdapter(getContext(),ListViewAdapter.TAG2);
        lv_top.setAdapter(top_adapter);
        lv_end.setAdapter(end_adapter);
        //循环find子View增加点击事件监听
        btn_group  =((LinearLayout) view.findViewById(R.id.broad_btn_box));
        for (int i = 0; i < btn_group.getChildCount(); i++) {
            Button button = (Button) view.findViewById(btnIds[i]);
            button.setOnClickListener(this);
        }
    }

    @Override
    public void onResponse(Call<BroadCastEntity> call, Response<BroadCastEntity> response) {
//        Log.i(TAG, "onResponse: "+(response.body().getData().getTopRadios().get(2).getPlayUrl().getTs24()));
        if (response.body()!=null) {
            adapter.addAll(response.body().getData().getCategories());
            top_adapter.addAll(response.body());
            end_adapter.addAll(response.body());
        }
    }

    @Override
    public void onFailure(Call<BroadCastEntity> call, Throwable t) {
        t.printStackTrace();
        Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.local_btn:
                String location = preferences.getString("location", "北京");
                intent.setClass(getContext(),LocalRadioActivity.class);
                intent.putExtra("provinceName",location);
                intent.putExtra("tag",LocalRadioActivity.LOCAL);
                break;
            case R.id.country_btn:
                intent.setClass(getContext(),LocalRadioActivity.class);
                intent.putExtra("tag",LocalRadioActivity.COUNTRY);
                break;
            case R.id.province_btn:
                intent.setClass(getContext(),ProvinceListActivity.class);
                break;
            case R.id.internet_btn:
                intent.setClass(getContext(),LocalRadioActivity.class);
                intent.putExtra("tag",LocalRadioActivity.INTERNET);
                break;
        }
        startActivity(intent);

    }
    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span=1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    @Override
    public void locationFinsh(String provinceName) {
        saveLocation(provinceName);
//        Log.i("1620", "locationFinsh: "+provinceName+provinceName.substring(0,provinceName.length()-1));
//        provinceCode = provinceMap.get(provinceMap.get(provinceName.substring(0,provinceName.length()-1)));
    }

    private void saveLocation(String provinceName) {
        this.provinceName = provinceName.substring(0,provinceName.length()-1);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("location",this.provinceName);
        editor.commit();
    }
}
